package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j

public class CategoryController {

    @Autowired
    ///weile xiugai
    private CategoryService categoryService;

    /**
     * 新增菜品或新增套餐类型
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("保存菜品信息成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        // 分页构造器
        Page<Category> pageInfo = new Page(page, pageSize);

        // 条件构造器对象
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 根据sort字段进行排序
        lambdaQueryWrapper.orderByAsc(Category::getSort);

        categoryService.page(pageInfo, lambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 删除某个菜品类型
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.removeById(id);
        return R.success("删除菜品信息成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category) {
//        log.info("cate==>{}", category);

        // 根据categoryid修改信息
        categoryService.updateById(category);
        return R.success("数据修改成功");
    }

    /**
     * 配合新增菜品，显示所有的菜品分类
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        // 获取category的type，根据type看是返回菜品分类还是套餐分类

        // 添加条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 添加条件
        lambdaQueryWrapper.eq(category.getType() != null, Category::getType, category.getType());

        // 添加排序条件
        lambdaQueryWrapper.orderByAsc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }
}
